import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 一、导入组件
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/Layout/Home')
const Question = () => import('@/views/Layout/Question')
const Video = () => import('@/views/Layout/Video')
const User = () => import('@/views/Layout/User')
const Search = () => import('@/views/Search')
const SearchResult = () => import('@/views/Search/result')
const Article = () => import('@/views/Article')
const UserProfile = () => import('@/views/Layout/User/profile')
const UserChat = () => import('@/views/Layout/User/chat')

Vue.use(VueRouter)

// 二、创建路由规则
const routes = [
  { path: '/login', component: Login, name: 'Login' },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: Home, name: 'Home', meta: { isKeepAlive: true } },
      { path: '/question', component: Question, name: 'Question' },
      { path: '/video', component: Video, name: 'Video' },
      { path: '/user', component: User, name: 'User' },
    ],
  },
  { path: '/search', component: Search, name: 'Search' },
  {
    path: '/searchResult/:keyword',
    component: SearchResult,
    name: 'SearchResult',
    props: true,
  },
  { path: '/article/:art_id', component: Article, name: 'Article', props: true },
  { path: '/userProfile', component: UserProfile, name: 'UserProfile' },
  { path: '/userChat', component: UserChat, name: 'UserChat' },
]

const router = new VueRouter({
  routes,
})

// 需要验证的路径
const AuthUrl = ['/user']

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = store.state.user.tokenInfo.token
  // 如果是去 /login, 判断 token 存不存在, 如果 token 存在说明登录过了, 直接跳转到首页
  if (to.path === '/login' && token) {
    next('/')
    return
  }
  // 如果是需要验证的页面,那就判断有没有token
  if (AuthUrl.includes(to.path)) {
    if (store.state.user.tokenInfo.token) {
      // 有token
      next()
    } else {
      // 没有就去登录
      next({
        path: '/login',
        query: {
          backto: to.fullPath,
        },
      })
    }
  } else {
    next()
  }
})

export default router
